/*
 * utility.java
 *
 *  Created on: 2017-5-4
 *      Author: liubo
 */
package com.example.dmtprotocollib;

import java.util.Arrays;

import android.util.Log;

public class utility {
	private static final String DMTLogTAG="DMT_POC";
	
	public static byte[] hexToBytes(String hexString) {
		if (hexString == null || hexString.length() == 0) {
			return null;
		}
		char[] hex = hexString.toCharArray();
		int length = hex.length / 2;
		byte[] rawData = new byte[length];
		for (int i = 0; i < length; i++) {
			int high = Character.digit(hex[i * 2], 16);
			int low = Character.digit(hex[i * 2 + 1], 16);
			int value = (high << 4) | low;
			if (value > 127) {
				value -= 256;
			}
			rawData[i] = (byte) value;
		}
		return rawData;
	}
	
	public static int getUnsignedByte(byte b) {
		return (int)(b & 0xFF);
	}
	
	public static final String bytesToHexString(byte[] buf) {
		return bytesToHexString(buf, buf.length);
	}
	
	public static final String bytesToHexString(byte[] buf, int length) {
		if (buf == null || buf.length < length || length == 0)
		{
			return null;
		}
		
		StringBuilder sb = new StringBuilder(length * 2);
		String tmp = "";
		for (int i = 0; i < length; i++) {
			tmp = Integer.toHexString(0xff & buf[i]);
			tmp = tmp.length() == 1 ? "0" + tmp : tmp;
			sb.append(tmp);
		}
		return sb.toString();
	}
	
    private static String bytestoHexString(byte[] src,int len)
    {
    	StringBuilder stringBuidler=new StringBuilder("");
    	if(src==null||src.length<=0)
    	{
    		return null;
    	}
    	
    	for(int i=0;i<len;i++)
    	{
    		int v=src[i]&0xFF;
    		String hv=Integer.toHexString(v);
    		if(hv.length()<2)
    		{
    			stringBuidler.append(0);
    		}
    		stringBuidler.append(hv);
    	}
    	
    	return stringBuidler.toString();
    }
    
    public static final void Byte_Log(String inf,byte[] data,int len)
    {    	
    	if(data==null)
    	{
    		return ;
    	}
    	String hexdata= bytestoHexString(data,len);    	
    	Log.d(DMTLogTAG, inf+hexdata);    	
    }
 
    public static final void Byte_Log(String inf,byte[] data,int pos,int len)
    {    	
    	if(data==null||data.length<(pos+len))
    	{
    		return ;
    	}
    	byte[] tmpbuf=new byte[len];
    	System.arraycopy(data, pos, tmpbuf, 0, len);
    	String hexdata= bytestoHexString(tmpbuf,len);    	
    	Log.d(DMTLogTAG, inf+hexdata);    	
    }    
    
    public static final void Byte_Log(String inf,byte[] data)
    {    
    	if(data==null)
    	{
    		return ;
    	}
    	String hexdata= bytestoHexString(data,data.length);    	
    	Log.d(DMTLogTAG, inf+hexdata);    	
    }   
    
    public static final void Byte_Log(String inf,byte data)
    {    	
    	byte[] tmpbuf={data}; 
    	String hexdata= bytestoHexString(tmpbuf,1);    	
    	Log.d(DMTLogTAG, inf+hexdata);    	
    } 	

	
}
